from google.appengine.api import urlfetch
from django.utils import simplejson as json

class Mendeley:
    '''Mendeley open client for algos'''
    
    REQUEST_TOKEN_URL = 'http://www.mendeley.com/oauth/request_token/'
    ACCESS_TOKEN_URL  = 'http://www.mendeley.com/oauth/access_token/'
    AUTHORIZATION_URL = 'http://www.mendeley.com/oauth/authorize/'
    
    
    CONSUMER_KEY = "consumer_key=291612bf38c356c144e6c2d146125cba04d8c4a71"
    CONSUMER_SECRET = "614e9d5d29f5c505aadde5223ba7ed94"
    
    GROUP_ID     = '981951'
    PUBLIC_GROUP_METHODS = {
        "details"   : 'http://api.mendeley.com/oapi/documents/groups/' + GROUP_ID ,
        "documents" : 'http://api.mendeley.com/oapi/documents/groups/' + GROUP_ID + '/docs/'
    }
     
    def getGroupDocuments (self):
        '''
        JSON object with the following structure:
            'current_page': int.
            'documents': array of documents. Each document is a JSON object with the following fields 
                (if available): 'abstract', 'authors' (array), 'editors' (array), 'id', 'issue', 
                                'keywords' (array), 'pages', 'publisher', 'tags' (array), 'title', 
                                'type', 'url', 'uuid' (canonical id), 'volume', 'year'.
            'items_per_page': number of documents returned per page.
            'total_pages': number of total pages
            'total_results': total documents in the group.
        '''
        result   = None
        url      = self.PUBLIC_GROUP_METHODS['documents'] + '?details=true&' + self.CONSUMER_KEY
        response = urlfetch.fetch(url)
        self.last_status_code = response.status_code
        if response.status_code == 200:
            result = json.loads(response.content);
        return result;
    
    def processGroupDocumentsToExhibitJson(self):
        s = {}
        content = self.getGroupDocuments();
        if content:
            docs_list = content['documents']
            s = {"items" : map(lambda item: item.update({"label" : item.get('id')}) or item , docs_list)}
        return json.dumps(s)
    
    def __init__(self):
        self.last_status_code = None;